package service

import (
	"errors"

	"mutu/misc"
	"mutu/misc/log"
	"mutu/models"
)

type CommentManager struct {
}

var (
	CommentService = CommentManager{}
)

func (p CommentManager) AddComment(m *models.Comment) error {
	if m.Uuid == "" {
		m.Uuid = misc.NewUUID()
	}

	if _, err := models.Orm.Insert(m); err != nil {
		log.Log.Error("添加评论-保存出错，%s", err)
		return err
	}
	return nil
}

func (p CommentManager) RemoveComment(userId string, uuid string) error {
	m := &models.Comment{
		Uuid: uuid,
	}
	if err := models.Orm.Read(m, "Uuid"); err != nil {
		log.Log.Error("删除评论-读取原评论<%s>信息出错，%s", m.Uuid, err)
		return err
	}

	if m.UserId != userId {
		log.Log.Error("删除评论<%s>失败，没有权限", m.Uuid)
		return errors.New("没有权限")
	}

	if _, err := models.Orm.Delete(m); err != nil {
		log.Log.Error("删除评论<%s>失败，%s", m.Uuid, err)
		return err
	}
	return nil
}

func (p CommentManager) GetRelComments(flag int, relid string) ([]*models.Comment, error) {

	var arr []*models.Comment
	_, err := models.Orm.QueryTable("Comment").Filter("Flag", flag).Filter("RelId", relid).All(&arr)
	if err != nil {
		log.Log.Error("读取<%d:%s>关联的评论出错，%s", flag, relid, err)
		return nil, err
	}
	return arr, nil
}

func (p CommentManager) GetUserComments(userId string) ([]*models.Comment, error) {

	var arr []*models.Comment
	_, err := models.Orm.QueryTable("Comment").Filter("UserId", userId).All(&arr)
	if err != nil {
		log.Log.Error("读取用户<%s>关联的评论出错，%s", userId, err)
		return nil, err
	}
	return arr, nil
}

func (p CommentManager) RemoveRelComments(flag int, relid string) (int, error) {

	count, err := models.Orm.QueryTable("Comment").Filter("Flag", flag).Filter("RelId", relid).Delete()
	if err != nil {
		log.Log.Error("删除<%d:%s>关联的评论出错，%s", flag, relid, err)
		return 0, err
	}
	return int(count), nil
}

func (p CommentManager) RemoveUserComments(userId string) (int, error) {

	count, err := models.Orm.QueryTable("Comment").Filter("UserId", userId).Delete()
	if err != nil {
		log.Log.Error("删除用户<%s>关联的评论出错，%s", userId, err)
		return 0, err
	}
	return int(count), nil
}
